package com.helpyoutimely.order;/**
 * ${PROJET_NAME}
 * Created by lixinkun on 16/4/13 15:42.
 * Email EricLi1235@gmail.com.
 */

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.helpyoutimely.R;
import com.helpyoutimely.entity.ConsultExpert;
import com.helpyoutimely.order.adapter.ExpertListAdapter;
import com.helpyoutimely.order.service.CountTimeService;
import com.helpyoutimely.pay.PayActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * User: lixinkun
 * Date: 2016-04-13
 * Time: 15:42
 * FIXME
 */
public class OrderActivity extends Activity implements View.OnClickListener{

    public static final String CountTime = "com.helpyputimely.CountTime";
    public static final String EndTime = "com.helpyputimely.EndTime";
    private String[] mGenders;
    private String[] mFields;
    private List<ConsultExpert> mLists;
    private ExpandableListView expertListView;
    private ImageButton btnBack;
    private ArrayAdapter<String> fieldsAdapter;
    private ArrayAdapter<String> gendersAdapter;

    private PhoneStateReceiver receiver;
    private ServiceReceiver mReceiver;
    private Timer timer;
    private TimerTask task;
    private Handler handler;
    private long currentTime;
    private long endTime;
    private long holdingTime;
    private LocalBroadcastManager mLocalBroadcastManager;
    private Spinner spGender;
    private Spinner spField;
    private ExpertListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_order);
        initData();
        initView();
        registerBroadCast();




    }

    private void initData(){
        mLists = new ArrayList<>();
        ConsultExpert expert = new ConsultExpert();
        expert.setName("李老师");
        expert.setOrdernums("5");
        expert.setPhone("15625016803");
        expert.setPlace("日本");
        expert.setRate(5);
        expert.setImg(R.drawable.zard1);
        expert.setTags("情感、网瘾、亲子沟通");
        expert.setDescription("日本专业心理医师，从事专业心理咨询超过10年，" +
                "处理过很多中学生家庭教育问题，比如早恋，神经病，网瘾等。" +
                "曾经把一个网瘾少女，从退学的边缘拯救回来，你说厉不厉害");
        mLists.add(expert);

        expert = new ConsultExpert();
        expert.setName("黄老师");
        expert.setOrdernums("5");
        expert.setPhone("13888888888");
        expert.setPlace("广东广州");
        expert.setRate(4);
        expert.setTags("成长烦恼、两性心理");
        expert.setImg(R.drawable.zard2);
        expert.setDescription("专业心理咨询10年，处理过很多中学生家庭教育问题，比如早恋，神经病，网瘾等");
        mLists.add(expert);

        mFields =  getResources().getStringArray(R.array.consult_array);
        mGenders = getResources().getStringArray(R.array.gender);

        fieldsAdapter = new ArrayAdapter<>(OrderActivity.this,
                android.R.layout.simple_dropdown_item_1line, mFields);
        gendersAdapter = new ArrayAdapter<>(OrderActivity.this,
                android.R.layout.simple_dropdown_item_1line,mGenders);

    }

    private void initView(){
        expertListView = (ExpandableListView) findViewById(R.id.lv_expert);
        spField = (Spinner) findViewById(R.id.sp_consult);
        spGender = (Spinner)  findViewById(R.id.sp_gender);
        btnBack = (ImageButton) findViewById(R.id.btn_back);
        btnBack.setOnClickListener(this);


        adapter = new ExpertListAdapter(mLists,this);
        expertListView.setAdapter(adapter);
        expertListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent i1 = new Intent(OrderActivity.this, PayActivity.class);
                startActivity(i1);
                return false;
            }
        });
        spField.setAdapter(fieldsAdapter);
        spGender.setAdapter(gendersAdapter);
    }

    class ServiceReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            endTime =  intent.getLongExtra(EndTime,0);
            countTime();
            Log.d("lixinkun","received endtime="+ endTime);
        }
    }

    private void registerBroadCast(){
        receiver = new PhoneStateReceiver();
        IntentFilter filter = new IntentFilter("android.intent.action.PHONE_STATE");
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(receiver,filter);


        mReceiver = new ServiceReceiver();
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter1 = new IntentFilter();
        filter.addAction(CountTime);
        registerReceiver(mReceiver, filter1);

    }



    private void countTime(){
        holdingTime = endTime - currentTime;
//        Toast.makeText(this,"holdingTime = "+ holdingTime,Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_back:
                finish();
                break;
            default:
                break;
        }
    }

    class PhoneStateReceiver extends BroadcastReceiver {
        private static final String TAG = "lixinkun";
        private int count = 0;

        @Override
        public void onReceive(Context context, Intent intent) {
            //如果是拨打电话
            if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
                String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Log.i(TAG, "call OUT:"+phoneNumber+"startSetvice");
                startTimerService();

                TelephonyManager tm1 =
                        (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
                switch (tm1.getCallState()) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        break;
                    //挂断
                    case TelephonyManager.CALL_STATE_IDLE:
                        gotoPay();
                        break;
                }
           } else if(intent.getAction().equals(CountTime)){

            } else {
                TelephonyManager tm =
                        (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                switch (tm.getCallState()) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:

                        countTime();
                        break;
                }
            }
        }
    }

    private void stopTimerService(){
        Intent intent = new Intent(OrderActivity.this, CountTimeService.class);
        stopService(intent);
    }

    private void startTimerService(){
        currentTime = System.currentTimeMillis();
        Intent intent = new Intent(OrderActivity.this, CountTimeService.class);
        startService(intent);
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d("lixinkun","pause");

    }

    @Override
    protected void onStop() {
        super.onStop();
//        startTimerService();
//        Log.d("lixinkun","stop->startService");
    }

    @Override
    protected void onRestart() {
//        stopTimerService();
        super.onRestart();

    }

    @Override
    protected void onResume() {

        stopTimerService();
        endTime = System.currentTimeMillis();
        countTime();
        Log.d("lixinkun","resume->stopService");
        super.onResume();
    }

    private void gotoPay(){
        Intent i = new Intent(OrderActivity.this,PayActivity.class);
        startActivity(i);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        unregisterReceiver(mReceiver);
    }
}
